/*
 * Copyright (c) 2012 Universidad Antonio de Nebrija.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License v2.0
 * which accompanies this distribution, and is available at
 * http://www.apache.org/licenses/LICENSE-2.0.html
 * 
 * Contributors:
 *    Universidad Antonio de Nebrija - initial API, implementation and documentation
 */
package com.nebrija.riif.model.saver.bufferedwriter;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.HashMap;

import com.nebrija.riif.model.ChildComponentUnit;
import com.nebrija.riif.model.RIIFElement;
import com.nebrija.riif.model.RIIFProperties;
import com.nebrija.riif.model.saver.ChildComponentUnitSaver;
import com.nebrija.riif.model.saver.RIIFSaverFactory;

/**
 * Implementation of an ChildComponentUnitSaver that writes the object to a BufferedWriter
 * @author asanchep
 *
 */
public class ChildComponentUnitWriterFormatSaver implements
		ChildComponentUnitSaver {

	public static final String CHILD_COMPONENT_TOKEN = "child_component";
	
	/** Writer where the information about the object is sent */
	private BufferedWriter out;
	/** Factory used to create other elements of the saver family */
	private RIIFSaverFactory factory;
	
	/**
	 * Creates an ChildComponentUnitWriterFormatSaver
	 * @param out Writer where the information about the object is sent
	 * @param factory Factory used to create other elements of the saver family
	 */
	public ChildComponentUnitWriterFormatSaver(BufferedWriter out,
			RIIFWriterFormatSaverFactory factory) {
		this.out=out;
		this.factory=factory;
	}

	@Override
	public void save(ChildComponentUnit element) {
		if(out==null){
			return;
		}
		try{
			//Write the child component token
			out.append(CHILD_COMPONENT_TOKEN).append(" ").append(element.getImplementedComponentName())
					.append(" ").append(element.getName()).append(";\n");
			// Print the assign information for the properties. They were defined in the implemented component
			for(RIIFElement xl:element.getElements().values()){
				RIIFProperties p = (RIIFProperties)xl;
				HashMap<String,Object> props = p.getProps();
				for(String key:props.keySet()){
					out.append(RIIFPropertiesWriterFormatSaver.ASSIGN_TOKEN).append(" ")
							.append(element.getName()).append("'").append(p.getName())
							.append(" = ").append(props.get(key).toString()).append(";\n");
				}
			}
			out.append("\n");
			out.flush();
		}catch(IOException ioe){
			ioe.printStackTrace();
		}
		

	}

}
